<template>
  <el-row>
    <el-col :span="12">
      <!--  商品图片-- 轮播图 -->
      <el-carousel trigger="click" height="400px">
        <el-carousel-item v-for="(item, index) in goods.picList" :key="index" style="text-align: center">
          <el-image
              :src="'/api/file/images/' + item.url"
              style="height: 400px"
              fit='contain'
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="goods.picList.map(pic => {return '/api/file/images/' + pic.url})"
              :initial-index="index"
              :preview-teleported="true"
          />
        </el-carousel-item>
      </el-carousel>
    </el-col>
    <el-col :span="12">
      <!--  商品基本信息  名字 颜色 版本 价格-->
      <div class="info">
        <div class="name">{{ goods.name }}</div>
        <div class="dscp">{{ goods.dscp }}</div>
        <!--<div class="price">{{ goods.price }}</div>-->
        <div class="price">售价:￥{{ goods.price }}</div>
        <div class="markPrice">原价:￥{{ goods.markPrice }}</div>
        <div class="color"><span>颜色: {{ goods.color }}</span></div>
        <div class="version"><span>版本: {{ goods.version }}</span></div>
        <div class="count">数量{{ goods.count }}</div>
        <div class="score">评分
          <el-rate
              v-model="goods.score"
              disabled
              show-score
              text-color="#FF6800"
              :colors="['#FF6800','#FF6800','#FF6800']"
              score-template="{value} 分"
          />
        </div>
        <div class="goodsBtn">
          <el-badge :value="cartNumber" :max="99" style="margin-top: 15px;margin-right: 15px;">
            <el-button size="large" type="primary" @click="addCart">
              <el-icon>
                <ShoppingCart/>
              </el-icon>
              加入购物车
            </el-button>
          </el-badge>
          <el-button size="large" type="success" @click="toCreateOrder">
            <el-icon>
              <Money/>
            </el-icon>
            直接购买
          </el-button>
          <el-button size="large" type="info" v-if="!collectInfo" @click="collect">
            <el-icon>
              <Star/>
            </el-icon>
            收藏
          </el-button>
          <el-button size="large" type="danger" v-else @click="cancelCollect">
            <el-icon>
              <StarFilled/>
            </el-icon>
            取消收藏
          </el-button>
        </div>
      </div>
    </el-col>
  </el-row>
  <el-row>
    <!--  商品详情、商品评价-->
    <el-tabs model-value="first" class="demo-tabs">
      <el-tab-pane label="商品详情" name="first"><span v-html="goods.detail"></span></el-tab-pane>
      <el-tab-pane label="商品评价" name="second">
        <!-- 评论列表 -->
        <div v-for="(comment, index) in comments" :key="index" @click="selectComment(comment)" class="comment-item">
          <div class="comment-header">
            <span>{{ comment.status === 1 ? "匿名用户" : comment.user.realname }}</span>
            <el-rate v-model="comment.score" disabled show-score/>
          </div>
          <p>{{ comment.content }}</p>

          <div v-for="(child, index) in comment.comment" :key="index"  class="comment-item">
            <div class="comment-header">
              <span>{{ child.status === 1 ? "匿名用户" : child.user.realname }}</span>
              <el-rate v-model="comment.score" disabled show-score/>
            </div>
            <p>{{ child.content }}</p>

          </div>
        </div>

        <!-- 追评输入框 -->
        <div v-if="replyTo">
          <el-input
              v-if="replyTo"
              v-model="replyContent"
              type="textarea"
              placeholder="输入您的追评内容"
          ></el-input>
          <el-checkbox v-model="isAnonymous">匿名</el-checkbox>
          <el-button v-if="replyTo" type="primary" @click="submitReply">提交追评</el-button>
          <el-button v-if="replyTo" type="primary" @click="closeReply">关闭追平</el-button>
        </div>
        <div v-else>
          <!-- 发布新评价输入框 -->
          <el-input v-model="newCommentContent" type="textarea" placeholder="发表您的评价"></el-input>
          <el-checkbox v-model="isAnonymous">匿名</el-checkbox>
          <el-button type="primary" @click="submitComment">发表评论</el-button>
        </div>

      </el-tab-pane>
    </el-tabs>
  </el-row>
</template>

<script setup>
import {useRoute} from "vue-router";
import goodsApi from "@/api/GoodsApi.js";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import collectApi from "@/api/collect.js";
import {userStore} from "@/stores/user.js";
import cartApi from "@/api/CartApi.js";
import router from "@/router/index.js";
import commentApi from "@/api/commentApi.js";
import {Document} from "@element-plus/icons-vue";

const route = useRoute()

// 获取路径传递的参数
console.log(route.query.id)

// 登录用户信息
const userInfo = userStore()

// 需要显示的商品
const goods = ref({})
// 商品收藏状态
const collectInfo = ref(null)
// 购物车中商品数量
const cartNumber = ref(0)

// 根据商品id获取商品详情
const getGoodById = () => {
  let id = route.query.id
  goodsApi.getById(id)
      .then(resp => {
        if (resp.code === 10000) {
          goods.value = resp.data
          //   获取当前商品收藏信息
          if (userInfo.userInfo) {
            getCollectInfo()
            getCartNumber()
          }
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 获取当前商品收藏
const getCollectInfo = () => {
  collectApi.getInfo(goods.value.id)
      .then(resp => {
        if (resp.code === 10000) {
          collectInfo.value = resp.data
        }
      })
}

// 收藏
const collect = () => {
  collectApi.add(goods.value.id)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getGoodById()
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 取消收藏
const cancelCollect = () => {
  collectApi.del(collectInfo.value.id)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getGoodById()
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 添加购物车
const addCart = () => {
  cartApi.addInfo(goods.value.id)
      .then(resp => {
        if (resp.code === 10000) {
          // ElMessage.success(resp.msg)
          getCartNumber()
          ElMessageBox.confirm(
              '加入成功，是否打开购物车',
              '提示',
              {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'info',
              }
          )
              .then(() => {
                router.push('/user/cart')
              })
              .catch(() => {

              })
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 获得购物车中商品数量
const getCartNumber = () => {
  cartApi.getCartNumber(goods.value.id)
      .then(resp => {
        if (resp.code === 10000) {
          cartNumber.value = resp.data
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 去直接购买页面
const toCreateOrder = () => {
  //
  let goodsId = route.query.id
  router.push({
    path: '/user/order',
    query: {
      goodsId
    }
  })
}

// 评价相关
const comments = ref([]); // 评论列表
const newCommentContent = ref(''); // 新评论内容
const isAnonymous = ref(false); // 是否匿名
const replyTo = ref(null); // 追评的目标评论ID
const replyContent = ref(''); // 追评内容

// 获取评论数据
const fetchComments = () => {
  commentApi.getList({ goodsId: route.query.id }).then(resp => {
    if (resp.code === 10000) {
      comments.value = resp.data;
    } else {
      ElMessage.error('加载评论失败');
    }
  });
};

// 选择追评
const selectComment = (comment) => {
  replyTo.value = comment.id;
  replyContent.value = '';
};

// 提交追评
const submitReply = () => {
  commentApi.addInfo({
    type: replyTo.value ? 1 : 0,
    parentId: replyTo.value,
    content: replyContent.value,
    goodsId: route.query.id,
    status: isAnonymous.value ? 1 : 0,
  }).then(resp => {
    if (resp.code === 10000) {
      ElMessage.success('追评成功');
      replyTo.value = null;
      replyContent.value = '';
      fetchComments();
    } else {
      ElMessage.error('追评失败');
    }
  });
};

// 关闭
const closeReply = () => {
  replyTo.value = null;
  replyContent.value = '';
  fetchComments();
}

// 提交新评论
const submitComment = () => {
  commentApi.addInfo({
    type: 0,
    content: newCommentContent.value,
    status: isAnonymous.value ? 1 : 0,
    goodsId: route.query.id,
    parentId: 0,
  }).then(resp => {
    if (resp.code === 10000) {
      ElMessage.success('评论成功');
      newCommentContent.value = '';
      fetchComments();
    } else {
      ElMessage.error('评论失败');
    }
  });
};


// 评价相关

getGoodById()
fetchComments();
</script>

<style scoped>
.el-carousel {
  margin: 15px 0px;
//padding-top: 5px; border: 1px solid #AAAAAA;
}


.info {
  margin: 15px 25px;
}

.info div {
  margin-bottom: 15px;
}

.info .name {
  font-weight: bold;
  font-size: 20px;
}

.info .dscp {
  color: #999999;
}

.info .price {
  color: var(--theme-color);
  font-size: 18px;
}

.info .markPrice {
  color: #999999;
  font-size: 15px;
  text-decoration: line-through;
}

.info span {
  border: 2px solid var(--theme-color);
  line-height: 50px;
  padding: 0px 5px;
  border-radius: 5px;
  background-color: #FFFFFF;
}

.name, .price, .markPrice, .count, .score {
  margin: 10px;
}

.info .count {
  line-height: 15px;
}

.el-icon {
  margin-right: 3px;
}

.comment-item {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  cursor: pointer;
}
.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>